import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class SkillImporter {

	private static String webaddress = "https://api.eveonline.com/eve/SkillTree.xml.aspx";
	private List<Group> groups;
	public SkillImporter() {
		groups = new ArrayList<Group>();
	}
	
	public void Import() throws Exception {
		/*URL url = new URL(webaddress);
		URLConnection con = url.openConnection();
		
		Object obj = con.getContent();
		InputStreamReader reader = new InputStreamReader((InputStream)obj);
		BufferedReader bi = new BufferedReader(reader);
		
		String line;
		int count = 0;
		while ((line = bi.readLine()) != null) {
			if (line.contains("<result>")) {
				while(!line.contains("</result>") && (line = bi.readLine()) != null) {
					if (line.contains("<rowset") && line.contains("groupName")) {
						String changedLine = line.replaceAll("<", "");
						changedLine = changedLine.replaceAll(">", "").trim();
						String[] splitLine = changedLine.split(" ");
						
						String name = splitLine[1].replaceAll("name=", "").replaceAll("\"", "");
						String key = splitLine[2].replaceAll("key=", "").replaceAll("\"", "");
						String[] columns = splitLine[3].replaceAll("columns=", "").replaceAll("\"", "").split(",");
						mainGroup = new Group(name, key, columns);
					} else if (line.contains("<row")) {
						// TODO Continue Here
						String changedLine = line.replaceAll("<", "");
						changedLine = changedLine.replaceAll(">", "").trim();
						String[] splitLine = changedLine.split(" ");
						
						String name = splitLine[1].replaceAll("name=", "").replaceAll("\"", "");
						String key = splitLine[2].replaceAll("name=", "").replaceAll("\"", "");
						String[] columns = splitLine[3].replaceAll("name=", "").replaceAll("\"", "").split(",");
						// What do I do with these?
					}
				}
				break;
			}
		}
		System.out.println(count);*/
		
		
		File file = new File("Data/skills.xml");
		DocumentBuilderFactory dbFac = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFac.newDocumentBuilder();
		Document doc = dBuilder.parse(file);
		//doc.getDocumentElement().normalize();
		
		NodeList nList = doc.getElementsByTagName("row");
		//nList = nList.item(0).getChildNodes().item(3).getChildNodes().item(1).getChildNodes();
		for (int i = 0; i < nList.getLength(); i++) {
			Node nNode = nList.item(i);
			
			if (containsAttributeWithName(nNode, "groupName")) {
				int groupID = Integer.parseInt(nNode.getAttributes().getNamedItem("groupID").getNodeValue());
				Group group = getGroupByID(groupID);
				if (group == null) {
					groups.add(new Group(nNode.getAttributes().getNamedItem("groupName").getNodeValue(), groupID));
				}
			} else if (containsAttributeWithName(nNode, "published")) {
				NamedNodeMap map = nNode.getAttributes();
				String typeName = map.getNamedItem("typeName").getNodeValue();
				int groupID = Integer.parseInt(map.getNamedItem("groupID").getNodeValue());
				int typeID = Integer.parseInt(map.getNamedItem("typeID").getNodeValue());
				boolean published = map.getNamedItem("published").getNodeValue().equals("1"); 
				
				Skill newSkill = new Skill(typeName, typeID, groupID, published);
				
				getGroupByID(groupID).addSkill(newSkill);
				
				NodeList children = nNode.getChildNodes();
				for (int j = 0; j < children.getLength(); j++) {
					Node current = children.item(j);
					String name = current.getNodeName();
					if (name.equals("description")) {
						String description = "";
						if (current.hasChildNodes()) {
							description = current.getFirstChild().getTextContent();
						}
						newSkill.setDescription(description);
					} else if (name.equals("rank")) {
						newSkill.setRank(Integer.parseInt(current.getFirstChild().getTextContent()));
					} else if (name.equals("requiredAttributes")) {
						NodeList attributeChildren = current.getChildNodes();
						for (int k = 0; k < attributeChildren.getLength(); k++) {
							Node attributeNode = attributeChildren.item(k);
							String attributeName = attributeNode.getNodeName();
							if (attributeName.equals("primaryAttribute")) {
								newSkill.setPrimaryAttribute(attributeNode.getFirstChild().getTextContent());
							} else if (attributeName.equals("secondaryAttribute")) {
								newSkill.setSecondaryAttribute(attributeNode.getFirstChild().getTextContent());
							}
						}
					} else if (name.equals("rowset")) {
						if (!current.hasChildNodes()) { continue; }
						if (containsAttributeWithName(current.getChildNodes().item(1), "skillLevel")) {
							for (int k = 0; k < current.getChildNodes().getLength(); k++) {
								Node requiredSkillNode = current.getChildNodes().item(k);
								if (!requiredSkillNode.hasAttributes()) { continue; }
								newSkill.addRequiredSkill(Integer.parseInt(requiredSkillNode.getAttributes().getNamedItem("typeID").getNodeValue()));
								newSkill.addRequiredLevel(Integer.parseInt(requiredSkillNode.getAttributes().getNamedItem("skillLevel").getNodeValue()));
							}
						} else if (containsAttributeWithName(current.getChildNodes().item(1), "bonusType")) {
							// handle bonuses
							for (int k = 0; k < current.getChildNodes().getLength(); k++) {
								Node bonusNode = current.getChildNodes().item(k);
								if (!bonusNode.hasAttributes()) { continue; }
								newSkill.addBonusType(bonusNode.getAttributes().getNamedItem("bonusType").getNodeValue());
								newSkill.addBonusValue(Double.parseDouble(bonusNode.getAttributes().getNamedItem("bonusValue").getNodeValue()));
							}
						}
					}
				}
			}
		}
	}
	
	public boolean containsAttributeWithName(Node node, String name) {
		boolean retVal = false;
		
		NamedNodeMap list = node.getAttributes();
		
		for (int i = 0; i < list.getLength(); i++) {
			if (list.item(i).getNodeName().equals(name)) {
				retVal = true;
				break;
			}
		}
		
		return retVal;
	}
	
	public void createXMLFile() throws Exception {
		URL url = new URL(webaddress);
		URLConnection con = url.openConnection();
		InputStreamReader reader = new InputStreamReader(con.getInputStream());
		BufferedReader bi = new BufferedReader(reader);
		StringBuffer output = new StringBuffer();
		
		
		String line;
		while ((line = bi.readLine()) != null) {
			output.append(line + '\n');
		}
		
		File file = new File("Data/skills.xml");
		FileWriter writer = new FileWriter(file);
		writer.write(output.toString());
		writer.close();
	}
	
	public Group getGroupByID(int groupID) {
		Group group = null;
		for (int i = 0; i < groups.size(); i++) {
			if (groups.get(i).getGroupID() == groupID) {
				group = groups.get(i);
			}
		}
		return group;
	}

	public static void main(String[] args) throws Exception {
		SkillImporter imp = new SkillImporter();
		imp.Import();
	}

}
